package com.hongyi.system.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hongyi.common.framework.constant.UserConstans;
import com.hongyi.common.framework.domain.JsonResult;
import com.hongyi.common.framework.domain.LoginUser;
import com.hongyi.common.framework.exception.ServiceException;
import com.hongyi.common.framework.utils.StreamUtils;
import com.hongyi.common.framework.utils.bean.MapstructUtils;
import com.hongyi.common.framework.utils.common.ArrayUtils;
import com.hongyi.common.framework.utils.common.CollectionUtils;
import com.hongyi.common.framework.utils.common.ObjectUtils;
import com.hongyi.common.framework.utils.string.StringUtils;
import com.hongyi.common.mybatis.page.PageData;
import com.hongyi.common.mybatis.page.PageQuery;
import com.hongyi.common.saToken.utils.LoginUtils;
import com.hongyi.system.domain.SysDept;
import com.hongyi.system.domain.SysUser;
import com.hongyi.system.domain.SysUserPost;
import com.hongyi.system.domain.SysUserRole;
import com.hongyi.system.domain.dto.SysUserDto;
import com.hongyi.system.domain.vo.SysPostVo;
import com.hongyi.system.domain.vo.SysRoleVo;
import com.hongyi.system.domain.vo.SysUserVo;
import com.hongyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hongyi.system.service.ISysUserService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysPostMapper sysPostMapper;

    @Autowired
    private SysUserPostMapper sysUserPostMapper;

    private Wrapper<SysUser> buildQueryWrapper(SysUserDto user) {
        Map<String, Object> params = user.getParams();
        QueryWrapper<SysUser> wrapper = Wrappers.query();
        wrapper.eq("u.deleted", UserConstans.NORMAL)
                .eq(ObjectUtils.isNotNull(user.getUserId()), "u.user_id", user.getUserId())
                .like(StringUtils.isNotBlank(user.getUserName()), "u.user_name", user.getUserName())
                .eq(StringUtils.isNotBlank(user.getStatus()), "u.status", user.getStatus())
                .like(StringUtils.isNotBlank(user.getPhonenumber()), "u.phonenumber", user.getPhonenumber())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        "u.create_time", params.get("beginTime"), params.get("endTime"))
                .and(ObjectUtils.isNotNull(user.getDeptId()), w -> {
                    List<SysDept> deptList = sysDeptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                            .select(SysDept::getDeptId)
                            .apply(String.format("find_in_set('%s', '%s') <> 0", user.getDeptId(), "ancestors")));
                    List<Long> ids = StreamUtils.toList(deptList, SysDept::getDeptId);
                    ids.add(user.getDeptId());
                    w.in("u.dept_id", ids);
                }).orderByAsc("u.user_id");
        return wrapper;
    }

    /**
     * 获取用户列表
     *
     * @param sysUserDto 查询条件
     * @param pageQuery 分页参数
     * @return  用户列表
     */
    @Override
    public PageData<SysUserVo> selectPageUserList(SysUserDto sysUserDto, PageQuery pageQuery) {
        Page<SysUserVo> sysUserVoPage = sysUserMapper.selectPageUserList(pageQuery.build(), buildQueryWrapper(sysUserDto));
        return PageData.success(sysUserVoPage);
    }

    @Override
    public List<SysUserVo> selectUserList(SysUserDto sysUserDto) {
        return sysUserMapper.selectUserList(this.buildQueryWrapper(sysUserDto));
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUserVo selectUserById(Long userId) {
        return sysUserMapper.selectUserById(userId);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUserVo selectUserByUserName(String userName) {
        return null;
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, Long[] roleIds) {
        insertUserRole(userId, roleIds, true);
    }

    /**
     * 校验用户是否允许操作
     *
     * @param userId 用户ID
     */
    @Override
    public void checkUserAllowed(Long userId) {
        if (ObjectUtils.isNotNull(userId )&& LoginUtils.isAdmin(userId)) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 根据用户ID查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRoleVo> list = sysRoleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return StreamUtils.join(list, SysRoleVo::getRoleName);
    }

    /**
     * 根据用户ID查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPostVo> list = sysPostMapper.selectPostsByUserName(userName);
        if (CollUtil.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return StreamUtils.join(list, SysPostVo::getPostName);
    }

    /**
     * 新增用户
     *
     * @param sysUserDto 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public JsonResult<Void> saveUser(SysUserDto sysUserDto) {
        SysUser user = MapstructUtils.convert(sysUserDto, SysUser.class);
        //校验用户名唯一
        boolean userNameUnique = sysUserMapper.exists(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, user.getUserName())
                .ne(ObjectUtils.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId()));
        if (userNameUnique){
            return JsonResult.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        //校验手机号唯一
        if (StringUtils.isNotEmpty(user.getPhonenumber())){
            boolean userPhoneUnique = sysUserMapper.exists(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getPhonenumber, user.getPhonenumber())
                    .ne(ObjectUtils.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId()));
            if (userPhoneUnique){
                return JsonResult.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
            }
        }
        //校验邮箱唯一
        if (StringUtils.isNotEmpty(user.getEmail())){
            boolean userEmailUnique = sysUserMapper.exists(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getEmail, user.getEmail())
                    .ne(ObjectUtils.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId()));
            if (userEmailUnique){
                return JsonResult.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
            }
        }
        //用户密码加密
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        // 新增用户信息
        int result = sysUserMapper.insert(user);
        sysUserDto.setUserId(user.getUserId());
        //添加用户岗位信息
        insertUserPost(sysUserDto, false);
        // 新增用户与角色管理
        insertUserRole(sysUserDto, false);
        if (result > 0) {
            return JsonResult.ok();
        }else {
            return JsonResult.fail("用户添加失败,请稍后再试");
        }
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param sysUserDto 用户信息
     * @return 结果
     */
    @Override
    public boolean checkPhoneUnique(SysUserDto sysUserDto) {
        boolean exist = sysUserMapper.exists(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, sysUserDto.getUserName())
                .ne(ObjectUtil.isNotNull(sysUserDto.getUserId()), SysUser::getUserId, sysUserDto.getUserId()));
        return !exist;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param sysUserDto 用户信息
     */
    @Override
    public boolean checkEmailUnique(SysUserDto sysUserDto) {
        boolean exist = sysUserMapper.exists(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getPhonenumber, sysUserDto.getPhonenumber())
                .ne(ObjectUtil.isNotNull(sysUserDto.getUserId()), SysUser::getUserId, sysUserDto.getUserId()));
        return !exist;
    }

    /**
     * 修改用户
     *
     * @param sysUserDto 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public JsonResult<Void> editUser(SysUserDto sysUserDto) {
        SysUser user = MapstructUtils.convert(sysUserDto, SysUser.class);
        //校验用户名唯一
        boolean userNameUnique = sysUserMapper.exists(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, user.getUserName())
                .ne(ObjectUtils.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId()));
        if (userNameUnique){
            return JsonResult.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        //校验手机号唯一
        if (StringUtils.isNotEmpty(user.getPhonenumber())){
            boolean userPhoneUnique = sysUserMapper.exists(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getPhonenumber, user.getPhonenumber())
                    .ne(ObjectUtils.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId()));
            if (userPhoneUnique){
                return JsonResult.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
            }
        }
        //校验邮箱唯一
        if (StringUtils.isNotEmpty(user.getEmail())){
            boolean userEmailUnique = sysUserMapper.exists(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getEmail, user.getEmail())
                    .ne(ObjectUtils.isNotNull(user.getUserId()), SysUser::getUserId, user.getUserId()));
            if (userEmailUnique){
                return JsonResult.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
            }
        }
        //添加用户岗位信息
        insertUserPost(sysUserDto, true);
        // 新增用户与角色管理
        insertUserRole(sysUserDto, true);
        int result = sysUserMapper.updateById(user);
        if (result > 0) {
            return JsonResult.ok();
        }else {
            return JsonResult.fail("修改添加失败,请稍后再试");
        }
    }

    /**
     * 修改用户基本信息
     *
     * @param sysUserDto@return 结果
     */
    @Override
    public int updateUserProfile(SysUserDto sysUserDto) {
        return sysUserMapper.update(null,
                new LambdaUpdateWrapper<SysUser>()
                        .set(ObjectUtil.isNotNull(sysUserDto.getNickName()), SysUser::getNickName, sysUserDto.getNickName())
                        .set(SysUser::getPhonenumber, sysUserDto.getPhonenumber())
                        .set(SysUser::getEmail, sysUserDto.getEmail())
                        .set(SysUser::getSex, sysUserDto.getSex())
                        .eq(SysUser::getUserId, sysUserDto.getUserId()));
    }

    /**
     * 重置用户密码
     *
     * @param sysUserDto 用户信息
     * @return 结果
     */
    @Override
    public Boolean resetPwd(SysUserDto sysUserDto) {
        SysUser user = MapstructUtils.convert(sysUserDto, SysUser.class);
        checkUserAllowed(Objects.requireNonNull(user).getUserId());
        Objects.requireNonNull(user).setPassword(BCrypt.hashpw(user.getPassword()));
        return sysUserMapper.updateById(user)>0;
    }

    /**
     * 个人中心重置用户密码
     *
     * @param userId
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(Long userId, String password) {
        return sysUserMapper.update(null,
                new LambdaUpdateWrapper<SysUser>()
                        .set(SysUser::getPassword, password)
                        .eq(SysUser::getUserId, userId));
    }

    /**
     * 修改用户状态
     *
     * @param sysUserDto 用户信息
     * @return 结果
     */
    @Override
    public Boolean updateUserStatus(SysUserDto sysUserDto) {
        SysUser user = MapstructUtils.convert(sysUserDto, SysUser.class);
        checkUserAllowed(Objects.requireNonNull(user).getUserId());
        return sysUserMapper.updateById(user)>0;
    }

    @Override
    public boolean updateUserAvatar(Long userId, String avatar) {
        return sysUserMapper.update(null,
                new LambdaUpdateWrapper<SysUser>()
                        .set(SysUser::getAvatar, avatar)
                        .eq(SysUser::getUserId, userId)) > 0;
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(userId);
        }
        List<Long> ids = CollectionUtils.newArrayList(userIds);
        // 删除用户与角色关联
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, ids));
        // 删除用户与岗位表
        sysUserPostMapper.delete(new LambdaQueryWrapper<SysUserPost>().in(SysUserPost::getUserId, ids));
        // 防止更新失败导致的数据删除
        int flag = sysUserMapper.deleteBatchIds(ids);
        if (flag < 1) {
            throw new ServiceException("删除用户失败!");
        }
        return flag;
    }

    /**
     * 新增用户岗位信息
     *
     * @param sysUserDto  用户对象
     * @param clear 清除已存在的关联数据
     */
    private void insertUserPost(SysUserDto sysUserDto, boolean clear) {
        Long[] posts = sysUserDto.getPostIds();
        if (ArrayUtils.isNotEmpty(posts)) {
            if (clear) {
                // 删除用户与岗位关联
                sysUserPostMapper.delete(new LambdaQueryWrapper<SysUserPost>().eq(SysUserPost::getUserId, sysUserDto.getUserId()));
            }
            // 新增用户与岗位管理
            List<Long> postList = CollectionUtils.newArrayList(posts);
            List<SysUserPost> list = StreamUtils.toList(postList, postId -> {
                SysUserPost up = new SysUserPost();
                up.setUserId(sysUserDto.getUserId());
                up.setPostId(postId);
                return up;
            });
            sysUserPostMapper.insertBatch(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param sysUserDto  用户对象
     * @param clear 清除已存在的关联数据
     */
    private void insertUserRole(SysUserDto sysUserDto, boolean clear) {
        this.insertUserRole(sysUserDto.getUserId(), sysUserDto.getRoleIds(), clear);
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     * @param clear   清除已存在的关联数据
     */
    private void insertUserRole(Long userId, Long[] roleIds, boolean clear) {
        if (ArrayUtils.isNotEmpty(roleIds)) {
            // 判断是否具有此角色的操作权限
            List<SysRoleVo> roles = sysRoleMapper.selectRoleList(new LambdaQueryWrapper<>());
            if (CollectionUtils.isEmpty(roles)) {
                throw new ServiceException("没有权限访问角色的数据");
            }
            List<Long> roleList = StreamUtils.toList(roles, SysRoleVo::getRoleId);
            if (!LoginUtils.isAdmin(userId)) {
                roleList.remove(UserConstans.SUPER_ADMIN_ID);
            }
            List<Long> roleIdList = CollectionUtils.newArrayList(roleIds);
            List<Long> canDoRoleList = StreamUtils.filter(roleIdList, roleList::contains);
            if (CollectionUtils.isEmpty(canDoRoleList)) {
                throw new ServiceException("没有权限访问角色的数据");
            }
            if (clear) {
                // 删除用户与角色关联
                sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
            }
            // 新增用户与角色管理
            List<SysUserRole> list = StreamUtils.toList(canDoRoleList, roleId -> {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                return ur;
            });
            sysUserRoleMapper.insertBatch(list);
        }
    }


}
